import { Footer } from '@/components';
import { genCaptcha, login } from '@/services/passport';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Helmet, history, useIntl, useModel } from '@umijs/max';
import { Alert, Image, message, Space, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import { FormInstance } from 'antd/lib';
import React, { useEffect, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import { setStorage } from '@/utils/storage';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const formRef = useRef<FormInstance>();
  const [errMsg, setErrMsg] = useState<string | undefined>();
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();
  const [captchaHash, setCaptchaHash] = useState<string>();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const changeCaptch = () => {
    genCaptcha().then((res) => {
      setCaptchaHash(res.data?.hash);
    });
  };

  const finish = async (values: PASSPORT.LoginForm) => {
    try {
      // 登录
      const res = await login({ ...values, captchaHash });
      if (res.code !== 0) {
        formRef.current?.setFieldValue('captchaCode', '');
        changeCaptch();
        setErrMsg(res.message || '登录失败');
        // message.error('登录失败，请重试！');
        return;
      }
      
      setStorage('identity', res.data);
      message.success('登录成功！');
      await fetchUserInfo();
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/');
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  useEffect(() => {
    changeCaptch();
  }, []);

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          formRef={formRef}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          title="控制面板"
          subTitle="管理中心"
          initialValues={{
            autoLogin: true,
          }}
          onFinish={finish}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
            ]}
          />
          {errMsg && <LoginMessage content={errMsg} />}
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined />,
            }}
            placeholder="输入用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
            }}
            placeholder="输入密码"
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />

          <Space.Compact>
            <ProFormText
              name="captchaCode"
              fieldProps={{
                size: 'middle',
                prefix: <LockOutlined />,
                maxLength: 6,
              }}
              placeholder="请输入验证码"
              rules={[
                {
                  required: true,
                  message: '请输入验证码!',
                },
                {
                  len: 6,
                  message: '请输入验证码!',
                },
              ]}
            />
            {captchaHash && (
              <Image
                src={`${window.configs?.api.uri}/captcha/image/${captchaHash}`}
                preview={false}
                style={{ width: 120, height: 30, marginLeft: 10, cursor: 'pointer' }}
                onClick={changeCaptch}
              />
            )}
          </Space.Compact>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
